package com.cc.mydlnademo

import android.app.AlertDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.cc.dlnalib.DLNAController
import com.cc.dlnalib.STATE_GRAB
import com.cc.dlnalib.STATE_PLAYING
import com.cc.dlnalib.timeToInt
import kotlinx.android.synthetic.main.fragment_control.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class PlayFragment : Fragment() {
    lateinit var playViewModel: PlayViewModel
    var isSeeking = false
    var volume = -1
    var maxVolume = -1

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        playViewModel = ViewModelProvider(
            activity!!,
            ViewModelProvider.NewInstanceFactory()
        ).get(PlayViewModel::class.java)
        return inflater.inflate(R.layout.fragment_control, container, false)
    }

    var dialog: AlertDialog? = null
    private val stateCallback: (state: String) -> Unit = {
        ivPlay.setImageResource(
            if (it == STATE_PLAYING) {
                tvTitle.text = playViewModel.getCurrentTitle()
                R.drawable.ic_pause
            } else {
                R.drawable.ic_play
            }
        )
        if (it == STATE_GRAB) {
            dialog?.dismiss()
            dialog = AlertDialog.Builder(context).setMessage("当前设备被抢占").create().also { it.show() }
        }
    }

    private val progressCallback: (progress: String, duration: String) -> Unit =
        { progress, duration ->
            sb.max = timeToInt(duration)
            if (!isSeeking) {
                sb.setProgress(timeToInt(progress))
            }
            tvProgress.setText("$progress/$duration")
        }

    private fun playNext() {
        playViewModel.playNext {
            Toast.makeText(context, "投屏成功", Toast.LENGTH_SHORT).show()
        }
    }

    private fun playPre() {
        playViewModel.playPre {
            Toast.makeText(context, "投屏成功", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        tvTitle.text = playViewModel.getCurrentTitle()
        sb.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                isSeeking = true
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
                isSeeking = false
                DLNAController.seek(seekBar.progress)
            }
        })
        ivPlay.setOnClickListener {
            DLNAController.togglePlay()
        }
        ivPre.setOnClickListener {
            playPre()
        }
        ivNext.setOnClickListener {
            playNext()
        }
        ivPlay.isSelected = DLNAController.currentState == STATE_PLAYING
    }

    override fun onResume() {
        super.onResume()
        DLNAController.addStateCallBack(stateCallback)
        DLNAController.addProgressCallBack(progressCallback)
    }

    override fun onStop() {
        super.onStop()
        DLNAController.removeStateCallBack(stateCallback)
        DLNAController.removeProgressCallBack(progressCallback)

    }

    fun onVolumeChange(isVolumeUp: Boolean) {
        GlobalScope.launch {
            if (volume == -1 || maxVolume == -1) {
                maxVolume = DLNAController.getMaxVolumeSync()
                volume = DLNAController.getVolumeSync()
            }
            volume = if (isVolumeUp) volume + 5 else volume - 5
            if (volume > maxVolume) {
                volume = maxVolume
            } else if (volume < 0) {
                volume = 0
            }
            DLNAController.setVolume(volume)
        }
    }
}